package com.tourism.user.cn.service.impl;
/*********************************************************************
 Copyright(c) 2024 All Rights Reserved .
 Author : liliang
 CreatedOn : 2024/12/31 0:01
 Email : 2061996582@qq.com
 Describe : 关于用户的Service层
 UseCase :
 Version : 2024|V1.0.0.0
 **********************************************************************/

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tourism.core.cn.config.JwtConfig;
import com.tourism.core.cn.dto.LoginDto;
import com.tourism.core.cn.dto.RegisterDto;
import com.tourism.core.cn.dto.RegisterResultDto;
import com.tourism.core.cn.entity.User;
import com.tourism.core.cn.exception.BusinessException;
import com.tourism.core.cn.utils.JwtUtil;
import com.tourism.user.cn.mapper.IUserMapper;
import com.tourism.user.cn.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author new
 * @date 2024/12/31 0:01
 */
@Service
public class UserServiceImpl extends ServiceImpl<IUserMapper, User> implements IUserService {
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RegisterResultDto register(RegisterDto registerDto) {
        // TODO: 实现用户注册逻辑

        //创建用户实体类
        User user = new User();
        user.setMobile(registerDto.getMobile());

        //设置默认为启用
        user.setStatus(1);
        //设置默认用户名
        user.setUsername(generateUsername());
        //设置默认昵称
        user.setNickname("用户" + RandomUtil.randomString(6));

        //如果提供了密码，则使用加密规则加密
        if (StrUtil.isNotBlank(registerDto.getPassword())) {
            //MD5加密方式
            user.setPassword(passwordEncoder.encode(registerDto.getPassword()));
        }

        //保存用户
        save(user);

        //生成token
        JwtUtil jwtUtil = new JwtUtil(jwtConfig);
        String token = jwtUtil.generateToken(user.getId(), user.getUsername());

        //返回结果
        return RegisterResultDto.builder()
                .token(token)
                .userId(user.getId())
                .needComplete(true)
                .build();
    }

    @Override
    public RegisterResultDto checkUserByMobile(String mobile) {
        // 查询用户是否存在
        User user = baseMapper.selectByMobile(mobile);
        if (user != null) {
            // 用户存在，生成token并返回
            //生成token
            JwtUtil jwtUtil = new JwtUtil(jwtConfig);
            String token = jwtUtil.generateToken(user.getId(), user.getUsername());

            //返回结果
            return RegisterResultDto.builder()
                    .token(token)
                    .userId(user.getId())
                    .needComplete(isNeedComplete(user))
                    .build();
        }
        return null;
    }

    @Override
    public RegisterResultDto loginByPassword(LoginDto loginDto) {
        // 1.查询用户是否存在
        User user = baseMapper.selectByUserName(loginDto.getUsername());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        //2.验证密码
        if (!passwordEncoder.matches(loginDto.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 3.生成token
        JwtUtil jwtUtil = new JwtUtil(jwtConfig);
        String token = jwtUtil.generateToken(user.getId(), user.getUsername());

        // 4.返回结果
        return RegisterResultDto.builder()
                .token(token)
                .userId(user.getId())
                .needComplete(isNeedComplete(user))
                .build();
    }

    private String generateUsername() {
        //当前时间戳+四位随机数保证唯一
        return "user_" + System.currentTimeMillis() + RandomUtil.randomNumbers(4);
    }

    /**
     * 判断用户是否需要完善信息
     */
    private boolean isNeedComplete(User user) {
        return StringUtils.isBlank(user.getNickname())
                || StringUtils.isBlank(user.getEmail())
                || user.getGender() == null;
    }
}
